package com.woniu108.valueAdded.service.impl;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.ObjectUtil;
import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniu108.carService.commos.util.*;
import com.woniu108.valueAdded.mapper.UserVipMapper;
import com.woniu108.valueAdded.model.UserVip;
import com.woniu108.carService.commos.model.PagePayParam;
import com.woniu108.valueAdded.service.UserVipService;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.Map;

/**
 * <p>
 * vip信息表 服务实现类
 * </p>
 *
 * @author yanxi
 * @since 2024-05-23
 */
@Service
public class UserVipServiceImpl extends ServiceImpl<UserVipMapper, UserVip> implements UserVipService {

    @Resource
    private AlipayUtil alipayUtil;
    @Resource
    private AlipayConfiguration alipayConfiguration;
    @Resource
    private RedisUtil redisUtil;
    @Resource
    private UserVipService userVipService;
    @Resource
    private RabbitTemplate rabbitTemplate;


    @Override
    public String payVip(String userId, Integer number) throws Exception {
        Double money= Double.valueOf(StaticData.VIP_PER_MONEY*number);
        //雪花数生成订单Id,存入redis,设置过期时间
        String orderNum= new Snowflake(1,1).nextIdStr();
        redisUtil.setString(RedisKey.vipOrder(orderNum),userId+","+number,15*60);
        PagePayParam payParam=new PagePayParam();
        payParam.setBody("汽车服务订单支付");
        payParam.setMoney(money);
        payParam.setNotifyUrl("http://h5mdc4.natappfree.cc/value-added/userVip/notify");
        payParam.setReturnUrl("http://localhost:80/swagger-ui.html");
        payParam.setOrderId(orderNum);
        payParam.setSubject("汽车服务");
        long exireTime= Date.from(LocalDateTime.now().plusMinutes(15).atZone(ZoneId.systemDefault()).toInstant()).getTime();
        long now=new Date().getTime();
        int minute=(int)((exireTime-now)/1000/60);
        if(minute<1){
            throw new Exception("订单超时");
        }
        Date date=new Date(exireTime);
        String expire=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date);
        payParam.setTimeExpire(expire);
        String form=alipayUtil.pagePay(payParam);
        return form;
    }

    @Override
    @Transactional
    public void payNotify(Map<String, String> map) throws Exception {
        boolean signVerified= AlipaySignature.rsaCheckV1(map, alipayConfiguration.getAlipayPublicKey(), "utf-8", "RSA2");
        if(signVerified){
            String status=map.get("trade_status");
            if("TRADE_SUCCESS".equals(status)){
                //返回 TRADE_SUCCESS 则支付成功
                //获取信息
                String orderNum=map.get("out_trade_no");
                String data = redisUtil.getString(RedisKey.vipOrder(orderNum));
                String[] strings = data.split(",");
                String userId = strings[0];
                Integer number = Integer.valueOf(strings[1]);
                //新增用户vip天数
                this.addUserVipDate(userId,number*30,false);
                //加入vip定时检测功能,每天检查vip天数,每30天补充免费次数
                rabbitTemplate.convertAndSend("check_vip_time_queue",userId);
            }
        }

    }

    @Override
    public void addUserVipDate(String userId, Integer vipDate,Boolean isGift) {
        UserVip userVip = userVipService.getById(userId);
        Integer freeNum=2;
        if(isGift) freeNum=0;
        if(ObjectUtil.isEmpty(userVip)){
            UserVip userVip1 = new UserVip();
            //未购买过vip的情况
            userVip1.setUserId(userId);
            userVip1.setVipLevelId(1);
            userVip1.setVipStartTime(LocalDateTime.now());
            userVip1.setVipEndTime(LocalDateTime.now().plusDays(vipDate.longValue()));
            userVip1.setVipScore(BigDecimal.ZERO);
            userVip1.setFreeNum(freeNum);
            userVipService.save(userVip1);
        }else if(userVip.getVipEndTime().isBefore(LocalDateTime.now())){
            //vip已过期的情况,会员等级会员积分保留
            userVip.setUserId(userId);
            userVip.setVipStartTime(LocalDateTime.now());
            userVip.setVipEndTime(LocalDateTime.now().plusDays(vipDate.longValue()));
            userVip.setFreeNum(freeNum);
            userVipService.updateById(userVip);
        }else if(userVip.getVipEndTime().isAfter(LocalDateTime.now())){
            //vip未过期的情况,结束时间延后,不更新免费次数
            userVip.setVipEndTime(userVip.getVipEndTime().plusDays(vipDate.longValue()));
            userVipService.updateById(userVip);
        }
    }
}
